package cn.wolfcode.business.service.impl;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import cn.wolfcode.business.domain.BusAppointment;
import cn.wolfcode.business.service.IBusAppointmentService;
import cn.wolfcode.business.util.DateUtil;
import cn.wolfcode.business.util.RegexUtils;
import cn.wolfcode.business.util.VehiclePlateNoUtil;
import cn.wolfcode.common.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.wolfcode.business.mapper.BusStatementMapper;
import cn.wolfcode.business.domain.BusStatement;
import cn.wolfcode.business.service.IBusStatementService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 结算单Service业务层处理
 *
 * @author lyh
 * @date 2025-09-22
 */
@Service
public class BusStatementServiceImpl implements IBusStatementService {
    @Autowired
    private BusStatementMapper busStatementMapper;
    @Autowired
    private IBusAppointmentService appointmentService;

    /**
     * 查询结算单
     *
     * @param id 结算单主键
     * @return 结算单
     */
    @Override
    public BusStatement selectBusStatementById(Long id) {
        return busStatementMapper.selectBusStatementById(id);
    }

    /**
     * 查询结算单列表
     *
     * @param busStatement 结算单
     * @return 结算单
     */
    @Override
    public List<BusStatement> selectBusStatementList(BusStatement busStatement) {
        String endActualArrivalTime = (String) busStatement.getParams().get("endActualArrivalTime");
        // 结束时间转换Date 类型
        Date date = DateUtil.parseDate(endActualArrivalTime, "yyyy-MM-dd");
        //结束时间 +1 天-1 秒
        Date addDay = DateUtil.changeDate(date, Calendar.DAY_OF_YEAR, 1);
        Date subSecond = DateUtil.changeDate(addDay, Calendar.SECOND, -1);
        // 日期类型在转换回字符串类型
        String endTime = DateUtil.Date2String(subSecond, "yyyy-MM-dd HH:mm:ss");
        //将转换的时间设置到结束时间
        busStatement.getParams().put("endActualArrivalTime", endTime);
        //传入IS_NOT_DELETE 字段
        busStatement.setIsDelete(BusStatement.IS_NOT_DELETE);
        return busStatementMapper.selectBusStatementList(busStatement);

    }

    /**
     * 新增结算单
     *
     * @param busStatement 结算单
     * @return 结果
     */
    @Override
    public int insertBusStatement(BusStatement busStatement) {    //1.前台和后台的验证后端都要验证一次，也叫合理化验证
        if (busStatement == null) {
            throw new RuntimeException("参数错误");
        }

        if (busStatement.getCustomerName() == null || busStatement.getCustomerPhone() == null
                || busStatement.getLicensePlate() == null || busStatement.getCarSeries() == null
                || busStatement.getServiceType() == null) {
            throw new RuntimeException("非法参数");
        }

        //2.验证车牌号
        if (VehiclePlateNoUtil.getVehiclePlateNo(busStatement.getLicensePlate()) == null) {
            throw new RuntimeException("车牌号格式错误");
        }

        //3.手机号合理验证
        if (!RegexUtils.isPhoneLegal(busStatement.getCustomerPhone())) {
            throw new RuntimeException("手机号码格式错误");
        }
        //4.到店时间需要早于当前系统时间
        Date nowDate = new Date();
        if (busStatement.getActualArrivalTime().before(nowDate)) {
            throw new RuntimeException("到店时间不能早于当前时间");
        }
        //5.关键字段校验
        busStatement.setStatus(BusStatement.STATUS_CONSUME);
        //6.设置新增的时候 IS_NOT_DELETE 是有效用户
        busStatement.setIsDelete(BusStatement.IS_NOT_DELETE);
        busStatement.setCreateTime(DateUtils.getNowDate());

        return busStatementMapper.insertBusStatement(busStatement);

    }

    /**
     * 修改结算单
     *
     * @param busStatement 结算单
     * @return 结果
     */
    @Override
    public int updateBusStatement(BusStatement busStatement) {     //1.前台和后台的验证后端都要验证一次，也叫合理化验证
        if (busStatement == null) {
            throw new RuntimeException("参数错误");
        }

        if (busStatement.getCustomerName() == null || busStatement.getCustomerPhone() == null
                || busStatement.getLicensePlate() == null || busStatement.getCarSeries() == null
                || busStatement.getServiceType() == null) {
            throw new RuntimeException("非法参数");
        }

        //2.验证车牌号
        if (VehiclePlateNoUtil.getVehiclePlateNo(busStatement.getLicensePlate()) == null) {
            throw new RuntimeException("车牌号格式错误");
        }

        //3.手机号合理验证
        if (!RegexUtils.isPhoneLegal(busStatement.getCustomerPhone())) {
            throw new RuntimeException("手机号码格式错误");
        }
        //4.到店时间需要早于当前系统时间
        Date nowDate = new Date();
        if (busStatement.getActualArrivalTime().before(nowDate)) {
            throw new RuntimeException("到店时间不能早于当前时间");
        }
        //5.只有状态是消费中才可以编辑操作
        BusStatement oldobj = this.selectBusStatementById(busStatement.getId());
        if (oldobj == null || oldobj.getStatus() == null || oldobj.getIsDelete() == null) {
            throw new RuntimeException("参数错误");
        }
        if (BusStatement.STATUS_PAID.equals(oldobj.getStatus()) ||
                (!oldobj.getStatus().equals(busStatement.getStatus()))) {
            throw new RuntimeException("只有消费中的结算单才能编辑操作");

        }   //6.设置修改的时候 IS_NOT_DELETE 是有效用户
        if (BusStatement.STATUS_PAID.equals(busStatement.getStatus())) {
            throw new RuntimeException("已支付结算单不能修改");
        }
        busStatement.setCreateTime(DateUtils.getNowDate());
        return busStatementMapper.updateBusStatement(busStatement);
    }

    /**
     * 批量删除结算单
     *
     * @param ids 需要删除的结算单主键
     * @return 结果
     */
    @Override
    public int deleteBusStatementByIds(Long[] ids) {
        return busStatementMapper.deleteBusStatementByIds(ids);
    }

    /**
     * 改为 软 软 软删除信息
     * 将is_delete字段设置为1
     *
     * @param id 结算单主键
     * @return 结果
     */
    @Override
    public int deleteBusStatementById(Long id) {
        if (id == null) {
            throw new RuntimeException("参数错误");
        }
        BusStatement statement = this.selectBusStatementById(id);
        if (statement == null || statement.getStatus() == null) {
            throw new RuntimeException("参数错误");
        }
        //删除操作必须是IS_DELETE=0 才能进行删除操作
        if (BusStatement.IS_DELETE.equals(statement.getIsDelete())) {
            throw new RuntimeException("状态是删除状态的结算单不可以进行删除操作");
        }
        if (BusStatement.STATUS_PAID.equals(statement.getStatus())) {

            throw new RuntimeException("状态是消费中结算单才可以删除");
        }
        return busStatementMapper.updateIsDelete(id, BusStatement.IS_DELETE);
    }

    /**
     * 修改结算单金额 总数量 折扣价
     *
     * @param statementId    结算单ID
     * @param totalAmount    总金额
     * @param totalQuantity  总数量
     * @param discountAmount 折扣价
     */
    @Override
    public void updateAmount(Long statementId, BigDecimal totalAmount, BigDecimal totalQuantity, BigDecimal discountAmount) {
        busStatementMapper.updateAmount(statementId, totalAmount, totalQuantity, discountAmount);
    }

    /**
     * 修改结算单支付状态
     *
     * @param statementId 结算单ID
     * @param payId       支付ID
     * @param date        支付时间
     * @param statusPaid  支付状态
     * @return
     */
    @Override
    public int updatePayStatus(Long statementId, Long payId, Date date, Integer statusPaid) {
        return busStatementMapper.updatePayStatus(statementId, payId, date, statusPaid);

    }

    /**
     * 根据预约单ID 创建结算单
     *
     * @param id 预约单ID
     * @return
     */
    @Override
    @Transactional

    public Long createOrSelectStatement(Long id) {
        // 合理化校验
        if(id == null){
            throw new RuntimeException("参数错误");
        }

        //根据预约单ID 查询预约单信息
        BusAppointment busAppointment = appointmentService.selectBusAppointmentById(id);
        if(busAppointment == null ) {
            throw new RuntimeException("参数错误");
        }
        //判断当前预约单ID 是否已经查询结算单
        BusStatement statement =busStatementMapper.selectByAppointmentId(id);
        //  查询到 说明生成过了
        //判断预约单ID 是否能查出结算单对象
        if(statement != null){
            if(!(BusAppointment.STATUS_SETTLED.equals(busAppointment.getStatus())||
                    BusAppointment.STATUS_PAID.equals(busAppointment.getStatus()))){
                throw new RuntimeException("当前预约单状态不可以进行结算操作");
            }
        }else{
            //没查询到 说明没有生成过结算单，此时 Bustatement statement 为空
            //判断预约单状态必须是已到店
            if(!BusAppointment.STATUS_ARRIVED.equals(busAppointment.getStatus())){
                throw new RuntimeException("异常！当前数据结算单状态必须是已结算或者已支付");
            }
            //将我们预约单数据赋值给 结算单
            statement = new BusStatement();
            statement.setCustomerName(busAppointment.getCustomerName());
            statement.setCustomerPhone(busAppointment.getCustomerPhone());
            statement.setActualArrivalTime(busAppointment.getActualArrivalTime());
            statement.setLicensePlate(busAppointment.getLicensePlate());
            statement.setCarSeries(busAppointment.getCarSeries());
            statement.setServiceType(busAppointment.getServiceType());
            statement.setInfo(busAppointment.getInfo());
            statement.setAppointmentId(id);
            statement.setStatus(BusStatement.STATUS_CONSUME); //设置状态为消费中
            busStatementMapper.insertBusStatement(statement); //将结算单数据插入到数据库中
            // 将预约单状态改为已结算
            appointmentService.updateStatus(id, BusAppointment.STATUS_SETTLED);
            }
        // 返回结算单的ID
           return statement.getId();
    }















}
